/*
 * Package il.ac.biu.cs.grossmm.impl.activeData
 * File SqlNodesetModification.java
 * 
 * This is a part of presence service framework prototype. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.impl.activeData;

import il.ac.biu.cs.grossmm.api.OperationFailedException;
import il.ac.biu.cs.grossmm.api.data.UpdateType;

import java.util.HashSet;
import java.util.Set;

public class SqlNodesetModification {
	final int index;

	final SqlNodeBase parent;

	final Set<SqlInnerNode>[] children;

	// long version = 0;
	// long mergedVersion = -1;

	@SuppressWarnings("unchecked")
	public SqlNodesetModification(SqlNodeBase parent, SqlManipulator man,
			int index) throws OperationFailedException {
		this.children = new Set[4];
		this.parent = parent;
		this.index = index;

		int n = UpdateType.UNCHANGED.ordinal();

		SqlMapping mapping = parent.mapping;

		// populate set of subnodes (meanwhile non-modified)
		Set<SqlInnerNode> subNodes = mapping.getSubnodes(parent, index);

		for (int i = 0; i < 4; i++) {
			if (i == n)
				children[n] = new HashSet<SqlInnerNode>(subNodes);
			else
				children[i] = new HashSet();
		}
	}

	public void moveTo(SqlNodeModification m2, UpdateType u) {

		UpdateType u0 = m2.updateType;
		if (u0 != null && u != UpdateType.ADDED)
			children[u0.ordinal()].remove(m2.node);

		children[u.ordinal()].add((SqlInnerNode) m2.node);
	}

	Set<SqlInnerNode> getMerged() {
		// HashSet<SqlInnerNode> merged = new
		// HashSet<SqlInnerNode>(children[0]);
		// merged.addAll(children[1]);
		// merged.addAll(children[2]);

		// return merged;

		return new MergedSet<SqlInnerNode>(children);
	}

}
